package com.compass.doctor.ui.consultation

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.activity.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import com.compass.doctor.R
import com.compass.doctor.base.BaseVBActivity
import com.compass.doctor.callback.OnCustomButtonClick
import com.compass.doctor.callback.OnTextChanged
import com.compass.doctor.databinding.ActivityCreateConsultationBinding
import com.compass.doctor.databinding.DoctorHeadItemBinding
import com.compass.doctor.ui.consultation.adapter.JoinDoctorAdapter
import com.compass.doctor.ui.consultation.viewmodel.ConsultationViewModel
import com.compass.doctor.ui.home.DoctorListActivity
import com.compass.doctor.ui.home.adapter.DoctorAdapter
import com.compass.doctor.ui.patient.PatientListActivity
import com.compass.doctor.utils.StringUtils
import com.compass.framework.constant.KEY_CONSULT_TYPE
import com.compass.framework.constant.REFRESH_LAUNCH
import com.compass.framework.constant.TIME_FIFTEEN_DAY
import com.compass.framework.constant.TIME_HOUR
import com.compass.framework.ext.divider
import com.compass.framework.ext.onClick
import com.compass.framework.glide.setUrlCircle
import com.compass.framework.manager.UserInfoManager
import com.compass.framework.model.CreateConsultation
import com.compass.framework.model.Doctor
import com.compass.framework.model.DoctorId
import com.compass.framework.model.PatientInfo
import com.compass.framework.utils.BigDecimalUtils
import com.compass.framework.utils.DateUtils
import com.compass.framework.utils.LiveDataBus
import com.compass.framework.utils.dpToPx
import com.compass.framework.utils.getColorFromResource
import com.loper7.date_time_picker.DateTimeConfig
import com.loper7.date_time_picker.dialog.CardDatePickerDialog


/**
 * Description： 创建会诊
 * Date:2023/12/22 11:25
 */
class CreateConsultationActivity : BaseVBActivity<ActivityCreateConsultationBinding>() {


    companion object {
        fun start(context: Context) {
            val intent = Intent(context, CreateConsultationActivity::class.java)
            context.startActivity(intent)
        }
    }

    private val consultationViewModel: ConsultationViewModel by viewModels()

    private lateinit var joinDoctorAdapter: JoinDoctorAdapter //加入医生adapter
    private var joinDoctors: ArrayList<Doctor> = ArrayList()
    private lateinit var recommendAdapter: DoctorAdapter//推荐医生列表

    private lateinit var doctor: Doctor//接收传递过来的数据
    private lateinit var patient: PatientInfo//接收传递过来的数据
    private var myPrice: String?=null//我的会诊费用

    //医生选择回调
    private val mActivityResultLauncherDoctor: ActivityResultLauncher<Intent>? =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
            if (it.resultCode == RESULT_OK) {
                it.data?.let { intent ->
                    doctor = intent.serializable("doctor")!!
                    if (!isAddDoctor(doctor)) {
                        joinDoctors.add(doctor)
                        joinDoctorAdapter.setData(joinDoctors)
                        computationalCosts()
                    }else{
                        showToast("该医生已经添加")
                    }


                }
            }
        }

    //患者选择回调
    private val mActivityResultLauncherPatient: ActivityResultLauncher<Intent>? =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
            if (it.resultCode == RESULT_OK) {
                it.data?.let { intent ->
                    patient = intent.serializable("patient")!!
                    patientId = patient.id
                    mBinding.tvPatientName.text = patient.name
                }
            }
        }

    private var patientId: String? = null//患者id
    private var dateTime: Long? = null//创建时间
    override fun initView(savedInstanceState: Bundle?) {

        joinDoctorAdapter = JoinDoctorAdapter()
        recommendAdapter = DoctorAdapter(1)

        mBinding.rcyRecommend.apply {
            layoutManager = LinearLayoutManager(this@CreateConsultationActivity)
            divider(getColorFromResource(R.color.color_d6d6d6), dpToPx(1), false)
            adapter = recommendAdapter
        }
        mBinding.rcyJoin.apply {
            layoutManager = LinearLayoutManager(this@CreateConsultationActivity)
            adapter = joinDoctorAdapter
        }
        initHeadView()
    }

    override fun intListener() {
        recommendAdapter.onItemClickListener = { view, position ->
            recommendAdapter.getItem(position)?.let {

                if (!isAddDoctor(it)) {
                    joinDoctors.add(it)
                    joinDoctorAdapter.setData(joinDoctors)
                    computationalCosts()
                }else{
                    showToast("该医生已经添加")
                }
            }
        }
        joinDoctorAdapter.setOnCustomBottomClick(object : OnCustomButtonClick {
            override fun onButtonCallBack(position: Int, msgType: String?) {
                joinDoctors.remove(joinDoctorAdapter.getItem(position))
                joinDoctorAdapter.setData(joinDoctors)
                computationalCosts()
            }
        })
        joinDoctorAdapter.setOnChangedCallBack(onTextChanged)//暂时留着
        mBinding.llDoctor.onClick {
            val intent = Intent(this, DoctorListActivity::class.java)
            intent.putExtra(KEY_CONSULT_TYPE, 1)
            mActivityResultLauncherDoctor?.launch(intent)
        }
        mBinding.llTime.onClick {
            showDataDialog()
        }
        mBinding.llPatient.onClick {
            val intent = Intent(this, PatientListActivity::class.java)
            intent.putExtra(KEY_CONSULT_TYPE, 1)
            mActivityResultLauncherPatient?.launch(intent)
        }
        mBinding.tvConfirm.onClick {
            if (patientId == null) {
                showToast("请选择患者")
                return@onClick
            }
            if (joinDoctors.isEmpty()) {
                showToast("请选择医生")
                return@onClick
            }
            val list = ArrayList<DoctorId>()
            for (doctor in joinDoctors) {
                list.add(DoctorId(doctor.id))
            }
            if (dateTime == null) {
                showToast("请选择会诊时间")
                return@onClick
            }

            showLoading()
            val createConsultation = CreateConsultation(
                type = "1",
                patientId = patientId,
                dateTime = dateTime,
                doctors = list
            )
            consultationViewModel.createConsultation(createConsultation)
//            loginMeeting()
        }

    }

    private fun isAddDoctor(doctor: Doctor): Boolean {
        for (item in joinDoctors) {
            if (item.id == doctor.id) {
                return true
            }
        }
        return false
    }


    private var onTextChanged = object : OnTextChanged {
        override fun onTextChange() {

//            LogUtil.e("修改了list的数据${joinDoctors[0].expense}")
        }
    }


    override fun initData() {
        consultationViewModel.createLiveData.observe(this) {
            dismissLoading()
            if (it) {
                showToast("创建成功")
                LiveDataBus.get().with(REFRESH_LAUNCH).postValue(REFRESH_LAUNCH)
                finish()
            }

        }
        consultationViewModel.recommendDoctorLiveData.observe(this) {
            recommendAdapter.setData(it)
        }
        consultationViewModel.recommendDoctor()
    }

    private lateinit var doctorHeadBinding: DoctorHeadItemBinding

    private fun initHeadView() {
        doctorHeadBinding = DoctorHeadItemBinding.inflate(LayoutInflater.from(this))
        joinDoctorAdapter.addHeadView(doctorHeadBinding.root)
        val user = UserInfoManager.getUserInfo()
        user?.let { userInfo ->

            doctorHeadBinding.imgDoctorHead.setUrlCircle(userInfo.avatar)
            doctorHeadBinding.tvDoctorName.text = userInfo.getNameString()
            doctorHeadBinding.tvHospital.text = "${userInfo.getHospitalNameString()}  ${userInfo.getDepartmentNameString()}"
            doctorHeadBinding.tvRank.text = userInfo.positionName

            userInfo.config?.let {
                myPrice = it.medicalConsultationPrice
                doctorHeadBinding.edtExpense.text = it.medicalConsultationPrice
            }


            computationalCosts()
        }

    }

    /**
     * 计算金额
     */
    private fun computationalCosts() {
        var drugsCost = "0"
        for (drug in joinDoctors) {
            drug.medicalConsultationPrice?.let {
                drugsCost = BigDecimalUtils.add(it, drugsCost, 2)
            }
        }
        if (myPrice.isNullOrEmpty()) {
            myPrice = "0.0"
        }
        drugsCost = BigDecimalUtils.add(myPrice, drugsCost, 2)
        mBinding.tvTotalFee.text = drugsCost


        mBinding.tvDoctors.text = getDoctors()?:"请选择会诊医生"

    }

    private fun getDoctors():String?{
        var names=ArrayList<String>()
        for (item in joinDoctors){
            names.add(item.name)
        }
        return names.joinToString(separator = "/")
    }

    /**
     * 设置会诊时间
     */
    private fun showDataDialog() {
        CardDatePickerDialog.builder(this)
            .setTitle("开始时间")
            .showBackNow(false)
            .setMinTime(System.currentTimeMillis()+TIME_HOUR)
            .setMaxTime(System.currentTimeMillis() + TIME_FIFTEEN_DAY)
            .setLabelText("年", "月", "日", "时", "分")
            .setBackGroundModel(CardDatePickerDialog.STACK)
            .setDisplayType(
                DateTimeConfig.YEAR,
                DateTimeConfig.MONTH,
                DateTimeConfig.DAY,
                DateTimeConfig.HOUR,
                DateTimeConfig.MIN
            )
            .setThemeColor(getColorFromResource(R.color.color_0165b8))
            .setOnChoose { milliecond ->
                dateTime = milliecond
                mBinding.tvTime.text = StringUtils.conversionTime(milliecond, DateUtils.FORMAT_TWO)
            }.build().show()
    }
}